package com.dd.ent.car.ui.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.comment.Comment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.util.HashMap;

/**
 * Created by Zengnianan on 2016/3/10.
 */
public class CommentDialog extends Dialog{

    private ImageLoader mImageLoader;
    private DisplayImageOptions mOptoins;

    private View mDialogView;
    private EditText mContentEt;
    private Button mSendBtn;
    private TextView mCountTv;
    private Comment mTargetComment;
    private HashMap<Long,String> cacheContents;
    private static final long NULL_KEY = -1;
    private OnDismissListener mExtDismissListener;
    private View mTargetLyt;
    private ImageView mTargetAvatarIv;
    private TextView mTargetContentTv;
    private TextView mQkTitleTv;
    private ImageView mRefreshIv;
    private View.OnClickListener mRefreshListener;
    private boolean mRefresable;

    public CommentDialog(Context context) {
        super(context);
        createView(context);
        mImageLoader = ImageLoader.getInstance();
        mImageLoader.init(ImageLoaderConfiguration.createDefault(context));
        mOptoins = initDisplayOption();
    }

    private void createView(Context context) {
        mDialogView = LayoutInflater.from(context).inflate(R.layout.comment_dialog, null);
        mDialogView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mDialogView.findViewById(R.id.lyt_wrap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //DO nothing,just intercept click event
            }
        });

        //快捷评论
        mQkTitleTv = (TextView)mDialogView.findViewById(R.id.tv_qk_title);
        mRefreshIv = (ImageView)mDialogView.findViewById(R.id.iv_refresh);
        mRefreshIv.setVisibility(View.GONE);
        mRefreshIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRefreshIv.setRotation(0);
                mRefreshIv.animate().rotation(360).setDuration(500);
                if(mRefreshListener != null){
                    mRefreshListener.onClick(v);
                }
            }
        });
        //引用部分
        mTargetLyt = mDialogView.findViewById(R.id.lyt_target);
        mTargetAvatarIv = (ImageView)mDialogView.findViewById(R.id.iv_avatar);
        mTargetContentTv = (TextView)mDialogView.findViewById(R.id.tv_target_content);

        //输入部分
        mContentEt = (EditText) mDialogView.findViewById(R.id.et_content);
        mCountTv = (TextView)mDialogView.findViewById(R.id.tv_left_count);
        mContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mCountTv.setText(s.length() + "/100");
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    if (mSendBtn.isEnabled()) {
                        mSendBtn.setEnabled(false);
                    }
                } else {
                    if (!mSendBtn.isEnabled()) {
                        mSendBtn.setEnabled(true);
                    }
                }
            }
        });
        mSendBtn = (Button) mDialogView.findViewById(R.id.btn_send);
    }


    private DisplayImageOptions initDisplayOption() {
        DisplayImageOptions.Builder builder = new DisplayImageOptions.Builder();
        builder.showImageOnLoading(R.drawable.default_user); // 设置在loading时的占位图
        builder.showImageForEmptyUri(R.drawable.default_user); // 设置图片为网络图片，而uri为空时的占位图
        builder.showImageOnFail(R.drawable.default_user); // 设置图片请求失败时的展位图
        builder.considerExifParams(true); // 设置是否考虑JPEG 类型图片的一下参数 如：rotate,
        // flip等
        builder.cacheInMemory(true); // 设置是否开启内存缓存
        builder.cacheOnDisc(true); // 设置是否开启磁盘缓存
        builder.displayer(new RoundedBitmapDisplayer(Integer.MAX_VALUE));
        return builder.build();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setCanceledOnTouchOutside(true);
        addView(getContext());
        cacheContents = new HashMap<>();
        super.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //cache content
                if(mTargetComment == null){
                    cacheContents.put(NULL_KEY,mContentEt.getText().toString());
                }else{
                    cacheContents.put(mTargetComment.getId(),mContentEt.getText().toString());
                }

                //处理外部监听
                if(mExtDismissListener != null){
                    mExtDismissListener.onDismiss(dialog);
                }
            }
        });
    }

    private void addView(Context context) {

        setContentView(mDialogView);
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        window.setWindowAnimations(R.style.bottom_dialog_animation);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        window.setBackgroundDrawable(dw);

        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;//(int)(137*context.getResources().getDisplayMetrics().density);
        window.setAttributes(lp);
    }

    @Override
    public void show() {
        super.show();

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

    }

    @Override
    public void setOnDismissListener(OnDismissListener listener) {
        mExtDismissListener = listener;
    }

    public void setOnSendButtonClickListener(View.OnClickListener listener){
        mSendBtn.setOnClickListener(listener);
    }

    public void setOnRefreshClickListener(View.OnClickListener listener){
        mRefreshListener = listener;
    }

    /**
     * 获取评论框里正在显示的内容
     * @return
     */
    public CharSequence getContent(){
        return mContentEt.getText().toString();
    }

    public void setContent(String content) {
        mContentEt.setText(content);
        if(!TextUtils.isEmpty(content)) {
            mContentEt.setSelection(content.length());
        }
    }

    public void setContentHint(String hint){
        mContentEt.setHint(hint);
    }

    public void setReplyTarget(Comment targetComment){
        if(targetComment == mTargetComment) return;
        if(targetComment != null && mTargetComment != null
                && targetComment.getId() == mTargetComment.getId()) return;

        mTargetComment = targetComment;
        //获取缓存
        String cache = null;
        if(mTargetComment != null) {
            cache =cacheContents.get(mTargetComment.getId());

            //显示引用内容
            mTargetLyt.setVisibility(View.VISIBLE);
            mTargetContentTv.setText(mTargetComment.getContent());
            String avatarPath = mTargetComment.getUserAvatar();
            if(!TextUtils.isEmpty(avatarPath)){
                mImageLoader.displayImage(avatarPath, mTargetAvatarIv, mOptoins);
            }
        }else{
            cache = cacheContents.get(NULL_KEY);
            mTargetLyt.setVisibility(View.GONE);
        }
        mContentEt.setText(cache);
        mContentEt.setSelection(cache == null ? 0 : cache.length());

    }

    public Comment getReplyTarget(){
        return mTargetComment;
    }


    public void setSendButtonText(CharSequence text){
        mSendBtn.setText(text);
    }

    public void setSendButtonEnabled(boolean enabled){
        mSendBtn.setEnabled(enabled);
    }

    public void clearCacheById(long parentCid) {
        if(cacheContents == null) return;
        if(parentCid == -1){
            cacheContents.remove(NULL_KEY);
        }else {
            cacheContents.remove(parentCid);
        }
    }

    public void clearAllCache(){
        if(cacheContents != null){
            cacheContents.clear();
        }
        mTargetComment = null;
        mContentEt.setText("");
        mContentEt.setHint("写评论...");
    }


}
